/**
 * 所有网盘的登陆类 单例
 * @author William
 * 2012-5-10
 */
package com.ytu.clouddisk.clientlogin;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.widget.Toast;

import com.google.api.client.googleapis.auth.clientlogin.ClientLogin;
import com.google.api.client.googleapis.auth.clientlogin.ClientLogin.ErrorInfo;
import com.google.api.client.http.HttpResponseException;
import com.ytu.clouddisk.face.Varibles;
import com.ytu.clouddisk.vdisk.VDiskControl;

public class LoginUtil {
	// static SharedPreferences sp =
	// c.getSharedPreferences(Varibles.CONFIG_FILE,Context.MODE_PRIVATE);
	/**
	 * GOOGle 账户登陆
	 * 
	 * @param type
	 * @return
	 * @throws IOException
	 */
	public static boolean GoogleLogin(Context c, String user, String psd) {
		ClientLogin clientLogin;
		ClientLogin.Response response;
		clientLogin = new ClientLogin();
		response = new ClientLogin.Response();
		clientLogin.accountType = "GOOGLE";
		clientLogin.applicationName = "CloudDisk";
		clientLogin.authTokenType = "writely";

		clientLogin.username = user;
		clientLogin.password = psd;
		try {
			response = clientLogin.authenticate();
			return c.getSharedPreferences(Varibles.CONFIG_FILE,
					Context.MODE_PRIVATE).edit()
					.putString(Varibles.GOOGLE_TOKEN, response.auth).commit();

		} catch (HttpResponseException httpE) {
			ErrorInfo info = null;
			try {
				info = httpE.response.parseAs(ClientLogin.ErrorInfo.class);
			} catch (IOException e) {
				Toast.makeText(c, "登陆失败" + e.getMessage(), Toast.LENGTH_LONG)
						.show();
			}
			Toast.makeText(c, "登陆失败" + info.error, Toast.LENGTH_LONG).show();
		} catch (Exception e) {
			Toast.makeText(c, "登陆失败" + e.getMessage(), Toast.LENGTH_LONG)
					.show();
		}
		return false;
	}

	/**
	 * 微盘的登陆
	 * 
	 * @param user
	 * @param psd
	 * @return
	 */
	public static boolean VDiskLogin(Context c, String user, String psd) {

		HttpPost httpRequest = new HttpPost(VDiskControl.makeURL("auth",
				"get_token"));
		ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
		postParams.add(new BasicNameValuePair("account", user));
		postParams
				.add(new BasicNameValuePair("appkey", Varibles.VDISK_APP_KEY)); // 封装入APPKey
		postParams.add(new BasicNameValuePair("password", psd));
		Long time1 = System.currentTimeMillis();
		String time = time1.toString().substring(0, 10);
		String strEncr = "account=" + user + "&appkey="
				+ Varibles.VDISK_APP_KEY + "&password=" + psd + "&time="
				+ time.toString();
		try {
			postParams.add(new BasicNameValuePair("signature", VDiskControl.encryptHMAC(
					strEncr, Varibles.VDISK_APP_SECRET)));
		} catch (Exception e) {
			Toast.makeText(c,"出错",Toast.LENGTH_SHORT);
			return false;
		}
		postParams.add(new BasicNameValuePair("time", time.toString()));
		try {
			httpRequest.setEntity(new UrlEncodedFormEntity(postParams,
					HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {
			Toast.makeText(c,"未知错误",Toast.LENGTH_SHORT);
			return false;
		}
		httpRequest.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		HttpClient httpclient = new DefaultHttpClient();
		String strResult = null;
		try {
			HttpResponse httpResponse = httpclient.execute(httpRequest);
			int statusCode = httpResponse.getStatusLine().getStatusCode(); // 获得200是正确
			if (statusCode == HttpStatus.SC_OK)
				strResult = EntityUtils.toString(httpResponse.getEntity());
		} catch (ParseException e) {
			Toast.makeText(c,"解析返回内容出错",Toast.LENGTH_SHORT);
			return false;
		} catch (IOException e) {
			Toast.makeText(c,"IO出错",Toast.LENGTH_SHORT);
			return false;
		}
		// Log.e("WeiboKu", "strResult :" + strResult);
		// json 解析解析出token
		JSONObject sData;
		try {
			sData = new JSONObject(strResult);
			JSONObject sD = sData.getJSONObject("data");
			return c.getSharedPreferences(Varibles.CONFIG_FILE,Context.MODE_PRIVATE).edit().putString(Varibles.VDISK_TOKEN, sD.getString("token")).commit();
		} catch (JSONException e) {
			Toast.makeText(c,"解析json数据出错",Toast.LENGTH_SHORT);
		}
		return false;
	}

	
}
